$(document).ready(function ($) {
    // Инициализируем все объекты/связи
    $('input[type="password"]').parents('form').on('submit', uzantoj_password_validation);
    $('input[type="password"]').on('keyup', uzantoj_password);
    $('input[name="chefa_retposhto"], input[name="chefa_telefonanumero"]').on('focusout', uzantoj_ajax_validation);

    $('#chefaRetposhtoFormo').on('hidden.bs.modal show.bs.modal', function () {
        $(this).find('input').prop('readonly', false).val('');
        $(this).find('button').prop('disabled', false);
        $('.carousel').carousel(0);
    });

    $('#newMail, #confirmCode').on('input', function (e) {
        $(this).popover('hide')
            .removeAttr('data-content');
    });

    $('#checkMail').on('click', function (e) {
        let new_mail = $('#newMail');
        $(this).prop('disabled', true);
        new_mail.prop('readonly', true);
        $.ajax({
        url: '/api/v1.1/',
        type: 'POST',
        async: true,
        cache: false,
        dataType: 'json',
        processData: true,
        data: {
            csrfmiddlewaretoken: getCookie('csrftoken'),
            query: 'mutation{changeMail(email: "' + new_mail.val() + '"){ status, message }}'
        }
    })
        .done(function (response) {
            if(response.data.changeMail.status) {
                // переходим на подтверждение действия
                $('.carousel').carousel(1);
            } else {
                // выводим ошибку со стороны сервера
                let new_mail = $('#newMail');
                let popover = new_mail.data('bs.popover');

                if(popover === undefined){
                    new_mail.popover({content: response.data.changeMail.message,
                        trigger: 'manual', placement: 'bottom'});
                    popover = new_mail.data('bs.popover');
                } else {
                    new_mail.attr('data-content', response.data.changeMail.message);
                    popover.setContent();
                }

                popover.show();
                new_mail.prop('readonly', false)
            }
        })
        .fail(function (jqXHR, textStatus){
            $('#newMail').prop('readonly', false).popover('show');
            console.log("Request failed: " + textStatus);
        });
        $('#checkMail').prop('disabled', false);
    });

    $('#retposhtoSlider').on('slid.bs.carousel', function (e) {
        if(e.to === 1) {
            let confirm = $('#confirmCode');
            let popover = confirm.data('bs.popover');
            let content = confirm.attr('data-content-origin');

            if(popover === undefined) {
                confirm.popover({content: content,
                        trigger: 'manual', placement: 'bottom'});
                popover = confirm.data('bs.popover');
            } else {
                confirm.attr('data-content', content);
                popover.setContent();
            }

            confirm.popover('show');
            setTimeout(function (e) {
                confirm.popover('hide');
            }, 10000);
        }
    });

    $('#сonfirmBtn').on('click', function (e) {
        let confirm = $('#confirmCode');
        let new_mail = $('#newMail');

        if(confirm.val().length) {
            confirm.prop('readonly', true);
            $(this).prop('disabled', true);

            $.ajax({
            url: '/api/v1.1/',
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            processData: true,
            data: {
                csrfmiddlewaretoken: getCookie('csrftoken'),
                query: 'mutation{changeMail(email: "' + new_mail.val() + '", confirm: "'
                        + confirm.val() + '"){ status, message }}'
            }
        })
            .done(function (response) {
                if(response.data.changeMail.status) {
                    $('#retposhtoSlider').carousel(2);
                    setTimeout(function (e) {
                        $('#changeMail').text(new_mail.val());
                        $('#chefaRetposhtoFormo').modal('hide');
                    }, 2000);
                } else {
                    let popover = confirm.data('bs.popover');

                    if(popover === undefined) {
                        confirm.popover({content: response.data.changeMail.message,
                        trigger: 'manual', placement: 'bottom'});
                    } else {
                        confirm.attr('data-content', response.data.changeMail.message)
                        popover.setContent();
                    }

                    confirm.prop('readonly', false).popover('show');
                    $('#сonfirmBtn').prop('disabled', false)
                }
            })
            .fail(function (jqXHR, textStatus) {
                console.log("Request failed: " + textStatus);
                confirm.prop('readonly', false);
                $('#сonfirmBtn').prop('disabled', false)
            });
        }
    });

    $('#sciigoj').on('change', function (e) {
        let target = $(this);

        target.prop('disabled', true)
            .attr('data-wait', true);

        $.ajax({
            url: '/api/v1.1/',
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            processData: true,
            data: {
                csrfmiddlewaretoken: getCookie('csrftoken'),
                query: 'mutation($poshto_sciigoj: Boolean){\n' +
                    '  changeUserSettings(poshtoSciigoj: $poshto_sciigoj){\n' +
                    '    status,\n' +
                    '    message,\n' +
                    '    poshtoSciigoj\n' +
                    '  }\n' +
                    '}',
                variables: JSON.stringify({
                    poshto_sciigoj: target.prop('checked')
                })
            }
        })
            .done(function (response) {
                if(response.data.changeUserSettings.status) {
                    target.prop('disabled', false)
                        .attr('data-wait', false);
                } else {
                    console.log('UserSettings: ' + response.data.changeUserSettings.message);
                    target.prop('checked', !target.prop('checked'))
                        .prop('disabled', false)
                        .attr('data-wait', false);
                }
            })
            .fail(function (jqXHR, textStatus) {
                console.log(textStatus);
                target.prop('checked', !target.prop('checked'));
            })
    })
});

function uzantoj_password(e) {
    var target = $(e.target);
    var fields = $('input[type="password"]');

    if(target.val().length) {
        $('input[type="password"]').attr('required', '');
        if($(fields[0]).val().length < 8) {
            $(fields[0]).addClass('bad_value');
        } else {
            $(fields[0]).removeClass('bad_value');
        }

        if($(fields[0]).val() !== $(fields[1]).val()) {
            $(fields[1]).addClass('bad_value');
        } else {
            $(fields[1]).removeClass('bad_value');
        }
    } else if(fields.length === 2 && !$(fields[0]).val().length && !$(fields[1]).val().length) {
        fields.removeAttr('required');
        fields.removeClass('bad_value');
    }
}

// Проверяем поля формы перед отправкой
function uzantoj_password_validation(e) {
    var fields = $(e.target).find('input[type="password"]');

    if(!$('.bad_value').length) {
        return true;
    }

    return false;
}

function uzantoj_ajax_validation() {
    var target = $(this);
    if(!target.val().length) {
        return;
    }

    $.ajax({
        url: window.location.href,
        type: 'POST',
        async: true,
        cache: false,
        dataType: 'json',
        processData: true,
        data: {
            csrfmiddlewaretoken: getCookie('csrftoken'),
            type: $(this).prop('name'),
            value: target.val()
        }
    })
        .done(function (response) {
            if($('input[name="' + response.type + '"]').val() == response.value) {
                if(response.status) {
                    target.removeClass('bad_value');
                    target.addClass('good_value');
                } else {
                    target.removeClass('good_value');
                    target.addClass('bad_value');
                }
            }
        })
        .fail(function (jqXHR, textStatus){
            console.log("Request failed: " + textStatus);
        });
}